//
//  PostAnswerViewController.m
//  MingShi
//
//  Created by MJiao on 15/7/6.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "PostAnswerViewController.h"
#import "KVNProgress.h"
#import "AFHTTPRequestOperationManager.h"
#import "ImgeUtil.h"
#import "UserManager.h"
#import "QuestionDetailViewController.h"
#import "SCNavigationController.h"
#import "PECropViewController.h"
#import "DataSourceManager.h"
#import "TOCropViewController.h"
#import "CommonUtils.h"

@interface PostAnswerViewController () <TOCropViewControllerDelegate>

@end

@implementation PostAnswerViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recvImagData:)
                                                 name:@"recvImagData"
                                               object:nil];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    singleTap.numberOfTapsRequired = 1;

    [self.ivAnswerPhtoto setUserInteractionEnabled:YES];
    [self.ivAnswerPhtoto addGestureRecognizer:singleTap];


    self.textView.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
    self.textView.layer.borderWidth = 1.0;

    self.textView.layer.cornerRadius = 5;
    self.textView.layer.masksToBounds = YES;

    self.textView.placeholder = @"请输入建议内容";
    [self.textView setText:@""];

}


- (void)tapDetected {
    //  [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:self];
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:nil];
    } else {
        SCNavigationController *nav = [[SCNavigationController alloc] init];
        nav.scNaigationDelegate = self;
        [nav showCameraWithParentController:self];

    }
}

- (void)didTakePicture:(SCNavigationController *)navigationController image:(UIImage *)image {
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [navigationController dismissModalViewControllerAnimated:NO];
    TOCropViewController *cropController = [[TOCropViewController alloc] initWithImage:image];
    cropController.delegate = self;
    [self presentViewController:cropController animated:YES completion:nil];
}

/**
* 裁剪图片后返回
*/
- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle {
    self.ivAnswerPhtoto.image = image;
    CGRect viewFrame = [self.view convertRect:self.ivAnswerPhtoto.frame toView:self.navigationController.view];

    [cropViewController dismissViewControllerAnimated:NO completion:^{

    }];
    self.isSelectedImage = YES;
    [[DataSourceManager shareDataSourceManager] setSelectImage:image];

    /// [[DataSourceManager shareDataSourceManager] setHasSelectedImage:YES];

}
- (void)didTakePictureOther {
    [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:nil];

}
- (void)recvImagData:(NSNotification *)notification {
    UIImage *uiImage = [notification.userInfo objectForKey:@"imageData"];
    if (uiImage) {
        self.isSelectedImage = YES;
        float frameWidth = self.ivAnswerPhtoto.frame.size.width;
        CGSize newSize = CGSizeMake(frameWidth, uiImage.size.height * frameWidth / uiImage.size.width);
        uiImage = [ImgeUtil imageWithImage:uiImage scaledToSize:newSize];

        CGRect oldRect = self.ivAnswerPhtoto.frame;

        self.ivAnswerPhtoto.frame = CGRectMake(oldRect.origin.x, oldRect.origin.y, newSize.width, newSize.height);

        [self.ivAnswerPhtoto setImage:uiImage];
        [self.ivAnswerPhtoto updateConstraintsIfNeeded];
        [self.ivAnswerPhtoto layoutIfNeeded];
    }
}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller {
    NSLog(@"---cropViewControllerDidCancel--");

    NSArray *viewControllers = self.navigationController.viewControllers;
    UIViewController *targetViewController = nil;
    for (id controller in viewControllers) {
        // 利用通知模式传递数据
        if ([controller isKindOfClass:[PostAnswerViewController class]]) {

            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];

            targetViewController = controller;
            break;
        }
    }
    if (targetViewController) {
        [self.navigationController popToViewController:targetViewController animated:YES];
    }
}

- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage {
    NSLog(@"----------cropViewController----------");

    [[DataSourceManager shareDataSourceManager] setSelectImage:croppedImage];

    [[DataSourceManager shareDataSourceManager] setHasSelectedImage:YES];

    NSArray *viewControllers = self.navigationController.viewControllers;
    UIViewController *targetViewController = nil;
    for (id controller in viewControllers) {

        // 利用通知模式传递数据
        if ([controller isKindOfClass:[PostAnswerViewController class]]) {

            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            [userInfo setObject:croppedImage forKey:@"imageData"];
            NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
            [notificationCenter postNotificationName:@"recvImagData" object:self userInfo:userInfo];
            targetViewController = controller;
            break;
        }
    }
    if (targetViewController) {
        [self.navigationController popToViewController:targetViewController animated:YES];
    }
}


- (IBAction)btnPostAnswerAction:(id)sender {
    NSString *content = [self.textView text];
    if (content == nil || content.length == 0) {
        [KVNProgress showErrorWithStatus:@"请填写您的答案"];
        [self.textView becomeFirstResponder];
        return;
    }

    [KVNProgress showWithStatus:@"答案发布中..."];

    if (!self.isSelectedImage) {
        [self uploadAttachParam:@""];
        return;
    }

    NSString *urlString = @"http://121.41.91.36:8888/api/help/upload";

    AFHTTPRequestOperationManager *httpManager = [[AFHTTPRequestOperationManager alloc] init];
    [httpManager.requestSerializer setTimeoutInterval:60];  //Time out after 25 seconds

//    NSData *imageData = UIImageJPEGRepresentation(self.ivAnswerPhtoto.image, 0.7);

    NSData *imageData = [CommonUtils imageWithImage:self.ivAnswerPhtoto.image scaled:0.7f];
    NSString *baseEncodedStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"imageUrl" : baseEncodedStr};

    [httpManager POST:urlString
           parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {

                NSString *content = [NSString stringWithCString:[responseObject bytes] encoding:NSUTF8StringEncoding];
                NSLog(@"ImageURL:%@", content);

                [self uploadAttachParam:content];

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"error:%@", error);
                // 结束登陆提示
                [KVNProgress dismiss];
                [KVNProgress showErrorWithStatus:@"请求失败,请重试"];
            }];


}

- (void)uploadAttachParam:(NSString *)imageUrl {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSInteger userId = [[[UserManager shareUserManager] curUser] userId];
    NSString *userIdStr = [NSString stringWithFormat:@"%ld", userId];
    NSString *helpIdStr = [NSString stringWithFormat:@"%ld", self.helpId];

    NSDictionary *parameters = @{
            @"userId" : userIdStr,
            @"imageUrl" : imageUrl,
            @"Contents" : [self.textView text],
            @"helpId" : helpIdStr
    };
    if (!imageUrl || imageUrl.length == 0) {
        parameters = @{
                @"userId" : userIdStr,
                @"Contents" : [self.textView text],
                @"helpId" : helpIdStr
        };
    }
    NSString *urlString = @"http://121.41.91.36:8888/api/answer/sethelp";
    [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }

        [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"] completion:^{

            //通知有新数据需要加载
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newDataNotify" object:self userInfo:[NSMutableDictionary dictionary]];

            NSArray *viewControllers = self.navigationController.viewControllers;
            UIViewController *targetViewController = nil;
            for (id controller in viewControllers) {
                if ([controller isKindOfClass:[QuestionDetailViewController class]]) {
                    targetViewController = controller;
                    break;
                }

            }
            if (targetViewController) {
                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
                [notificationCenter postNotificationName:@"recvRefreshFalg" object:self userInfo:userInfo];
                QuestionDetailViewController *questionDetailViewController = targetViewController;
                questionDetailViewController.refreshFalg = YES;

                [self.navigationController popToViewController:targetViewController animated:YES];
            } else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }];
    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
